<?php
	
	Class Yomm_Package_Install 
	{
		
		private $_pkg = null;
		
		private $_db = null;
		
		private $_return = null;
		
		private $error = array();
		
		public function __construct($pkg_array, $db)
		{
			$this->_pkg = $pkg_array;
			$this->_db = $db;
			$this->setError('installation of package: ' . print_r($this->_pkg, true));
		}
		
		public function installPackage()
		{
			if(!is_writable(Yomm_Config::DIR_PACKAGE_INSTALL) || !file_exists(Yomm_Config::DIR_PACKAGE_INSTALL))
			{
				$this->setError(Yomm_Config::DIR_PACKAGE_INSTALL . ' is not available or writeable');
				return false;	
			}
			
			$download = Tools::downloadAndStore($this->_pkg['file'], Yomm_Config::DIR_PACKAGE_INSTALL);
			
			if($download === false)
			{
				$this->setError('Download and save to local dir went wrong!');				
				return false;
			}
			
			$unzip = Tools::unzip($download);
			if($unzip === false)
			{
				$this->setError('Error while unzipping file');
				return false;
			}
			
			$dir = $unzip[0];
			$zip_folder_name = $unzip[1];
			
			$_tpl_folder = 'theme/' . SiteConfig::ActiveTheme . '/' . $zip_folder_name;
			
			if(!file_exists($_tpl_folder))
			{
				if(!Tools::createDir($_tpl_folder))
				{
					$this->setError('unable to create folder: ' . $_tpl_folder);
					return false;
				}
			}
			
			/*
			 * scan and install devmods
			 */
			$_dms = scandir($dir . '/devmods/');
			foreach($_dms as $dm)
			{
				if($dm == "." || $dm == "..")
					continue;
					
				$var = file_get_contents($dir . '/devmods/' . $dm);
				
				$gateway = new Yomm_Devmod_Import($this->_db);
				
				$return = $gateway->start($var);
				
				$raw_log = $gateway->getLog();
				
				new Yomm_Error($raw_log); // its not really an error - but it should display in the log file
			}
			
			/*
			 * scan and copy tpls
			 */
			
			
			
			$_tpls = scandir($dir . '/templates/');
			foreach($_tpls as $tpl)
			{
				if($tpl == "." || $tpl == "..")
					continue;
				
				Tools::copyFile($dir . '/templates/' . $tpl, $_tpl_folder . '/' . $tpl);
			}
			
			return true;
		}
		
		private function setError($message)
		{
			$this->error[] = $message;
		}
		
		public function getError()
		{
			return $this->error;
		}
		
		public function getReturn()
		{
			return $this->_return;
		}
	}